package com.github.eclipseace.mybatis.util;

import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.session.Configuration;

public final class BuilderUtils {
	private BuilderUtils() {
	}

	public static MappedStatement.Builder buildFrom(MappedStatement source, String id, SqlSource sqlSource,
			SqlCommandType sqlCommandType, Configuration configuration) {
		SqlSource newSqlSource = sqlSource != null ? sqlSource : source.getSqlSource();
		SqlCommandType newSqlCommandType = sqlCommandType != null ? sqlCommandType : source.getSqlCommandType();
		Configuration newConfiguration = configuration != null ? configuration : source.getConfiguration();
		return new MappedStatement.Builder(newConfiguration, id, newSqlSource, newSqlCommandType)
				.cache(source.getCache())
				.databaseId(source.getDatabaseId())
				.fetchSize(source.getFetchSize())
				.flushCacheRequired(source.isFlushCacheRequired())
				.keyColumn(StringUtils.joinWithComma(source.getKeyColumns()))
				.keyGenerator(source.getKeyGenerator())
				.keyProperty(StringUtils.joinWithComma(source.getKeyProperties()))
				.lang(source.getLang())
				.parameterMap(source.getParameterMap())
				.resource(source.getResource())
				.resultMaps(source.getResultMaps())
				.resultOrdered(source.isResultOrdered())
				.resultSets(StringUtils.joinWithComma(source.getResultSets()))
				.resultSetType(source.getResultSetType())
				.statementType(source.getStatementType())
				.timeout(source.getTimeout())
				.useCache(source.isUseCache());
	}

	public static MappedStatement.Builder buildFrom(MappedStatement source, String id, SqlSource sqlSource,
			SqlCommandType sqlCommandType) {
		return buildFrom(source, id, sqlSource, sqlCommandType, null);
	}

	public static MappedStatement.Builder buildFrom(MappedStatement source, String id, SqlSource sqlSource) {
		return buildFrom(source, id, sqlSource, null);
	}

	public static MappedStatement.Builder buildFrom(MappedStatement source, String id) {
		return buildFrom(source, id, null);
	}
}
